# -*- coding: utf-8 -*-

from datetime import datetime, timedelta

from django.conf import settings
from pymongo import MongoClient

from common.channel.admin_db import get_channel
from common.utils import track_logging

_LOGGER = track_logging.getLogger(__name__)

mg = MongoClient(settings.MONGO_ADDR).paychannel_stat


def get_user_channel_pay_count(mch_id, user_id, channel_id, day=datetime.now() + timedelta(hours=8)):
    id = day.strftime('%Y%m%d') + '_' + str(channel_id) + '_' + str(mch_id) + '_' + str(user_id)
    user_data = mg.user_status.find_one({"_id": id})
    if user_data:
        return user_data['count']
    else:
        return 0


def check_user_pay_count_is_over_limist(mch_id, user_id, channel_id):
    channel = get_channel(channel_id)
    if channel.user_day_order_count is None:
        return False
    if channel.user_day_order_count > get_user_channel_pay_count(mch_id, user_id, channel_id):
        return False
    else:
        return True


def record_channel_user_info(pay):
    create_time = pay.payed_at + timedelta(hours=8)
    id = create_time.strftime('%Y%m%d') + '_' + str(pay.channel_id) + '_' + str(pay.mch_id) + '_' + str(pay.user_id)
    user_data = mg.user_status.find_one({"_id": id})
    if user_data:
        mg.user_status.update({'_id': id}, {'$inc': {'count': 1, 'total': float(pay.total_fee)}})
    else:
        channel = get_channel(pay.channel_id)
        o = {}
        o['count'] = 1
        o['total'] = float(pay.total_fee)
        o['channel_id'] = pay.channel_id
        o['mch_id'] = int(pay.mch_id)
        o['channel_type'] = pay.channel_type
        if channel:
            o['channel_name'] = channel.name
            o['service_name'] = channel.service_name
            o['rate'] = float(channel.rate)
        o['created_at'] = datetime.strptime(
            "{}-{}-{} 0:0:0".format(create_time.year, create_time.month, create_time.day), "%Y-%m-%d %H:%M:%S")
        mg.user_status.update_one({'_id': id}, {'$set': o}, upsert=True)


def mg_channel_statistic(pay):
    create_time = pay.payed_at + timedelta(hours=8)
    id = str(pay.channel_id) + '_' + create_time.strftime('%Y%m%d')

    channel_daily_data = mg.channel_status.find_one({"_id": id})
    if channel_daily_data:
        mg.channel_status.update_one({'_id': id}, {'$inc': {'count': 1, 'total': float(pay.total_fee)}})
    else:
        o = {}
        o['count'] = 1
        o['total_count'] = 1
        end = datetime.utcnow() + timedelta(hours=8)
        o['end'] = end
        channel = get_channel(pay.channel_id)
        if channel:
            o['channel_name'] = channel.name
            o['service_name'] = channel.service_name
            o['rate'] = float(channel.rate)
        o['channel_type'] = pay.channel_type
        o['channel_id'] = pay.channel_id
        o['mch_id'] = int(pay.mch_id)
        o['total'] = float(pay.total_fee)
        o['start'] = datetime.strptime("{}-{}-{} 0:0:0".format(end.year, end.month, end.day), "%Y-%m-%d %H:%M:%S")
        mg.channel_status.update_one({'_id': id}, {'$set': o}, upsert=True)
    record_channel_user_info(pay)


def mg_channel_create_statistic(pay):
    now = datetime.utcnow() + timedelta(hours=8)
    id = str(pay.channel_id) + '_' + now.strftime('%Y%m%d')
    channel_daily_data = mg.channel_status.find_one({"_id": id})
    if channel_daily_data:
        mg.channel_status.update({'_id': id}, {'$inc': {'total_count': 1}})
    else:
        channel = get_channel(pay.channel_id)
        o = {}
        o['count'] = 0
        o['total_count'] = 1
        end = datetime.utcnow() + timedelta(hours=8)
        o['end'] = end
        if channel:
            o['channel_name'] = channel.name
            o['service_name'] = channel.service_name
            o['rate'] = float(channel.rate)
        o['channel_type'] = pay.channel_type
        o['channel_id'] = pay.channel_id
        o['mch_id'] = int(pay.mch_id)
        o['total'] = 0.0
        o['start'] = datetime.strptime("{}-{}-{} 0:0:0".format(end.year, end.month, end.day), "%Y-%m-%d %H:%M:%S")
        mg.channel_status.update_one({'_id': id}, {'$set': o}, upsert=True)
